<template>
    <el-dialog v-el-drag-dialog :title="form.id == 0 ? '新增目录' : '编辑目录'" :visible="visible" @update:visible="updateVisible" @closed="doCloseEdit">
        <el-form ref="addForm" hide-required-asterisk size="mini"
            :model="form" :rules="rules" :show-message="false" label-width="80px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="描述">
                <el-input type="textarea" v-model="form.comment" maxlength="100" :show-word-limit="false"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <bs-confirm-button-icon size="mini" @click.native="okClick" :text="'确定'" />
            <bs-cancel-button-icon size="mini" @click.native="doCloseEdit" />
        </div>
    </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
export default {
    data() {
        const valiName = (rule, value, callback) => {
            const reg = /^[a-zA-Z0-9\u4e00-\u9fa5]{1,20}$/
            if (reg.test(value)) {
                callback();
            } else {
                callback(new Error('只支持中文、字母、数字组合的20位字符组合'));
            }
        }
        return {
            rules: {
                name: [
                    { required: true, message: '名称不能为空' },
                    { validator: valiName }
                ]
            }
        }
    },
    directives: {
        elDragDialog
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        form: {
            type: Object,
            default: () => {}
        }
    },
    methods: {
        updateVisible(v) {
            this.$emit('update:visible', v)
        },
        doCloseEdit() {
            this.$refs.addForm.clearValidate()
            this.$refs.addForm.resetFields()
            this.updateVisible(false)
        },
        okClick() {
            this.$refs.addForm.validate((bool, err) => {
                if (bool) {
                    this.$emit('add', this.form)
                } else {
                    for(const key in err) {
                        this.$message.error(err[key][0].message)
                        break;
                    }
                }
            })
        }
    }
}
</script>

<style scoped>
::v-deep .el-dialog {
    width: 380px;
    height: 240px;
}
::v-deep .el-form {
    margin: 15px 15px 0 15px !important;
}
</style>
